package common

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
	"time"
	"wish_go/src/main/com/ajie/model"
)

var jwtKey = []byte(viper.GetString("jwt.secret"))

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

func GenerateToken(user model.User) (string, error) {
	claims := &Claims{
		UserId: user.Id,
		StandardClaims: jwt.StandardClaims{
			// 有效期
			ExpiresAt: time.Now().Add(viper.GetDuration("jwt.expiresAt") * time.Hour * 24).Unix(),
			// 创建时间
			IssuedAt: time.Now().Unix(),
			// 创建者
			Issuer: viper.GetString("server.author"),
			// 主体
			Subject: "user token",
		},
	}
	// 生成token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	str, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return str, nil
}

// 解析token
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, e error) {
		return jwtKey, nil
	})
	return token, claims, err
}
